package com.seecen.incerceptors;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String token = request.getHeader("token");
        log.info("LoginInterceptor====>{}",token);
        if(ObjectUtil.isNotEmpty(token)) {
            boolean isExpiration = jwtHelper.isExpiration(token);
            if(!isExpiration) return  true;
            Result ret = Result.build(null, ResultCode.NOTLOGIN);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(ret);
            response.getWriter().print(json);
            return false;
        }
        return true;
    }
}
